<template>
    <div class="content">
        <el-row class="title_block enterprise_info hpx-title-border">
            <span class="title_text">企业信息</span>
            <span class="col"><span class="hpx-label">企业名称：</span>{{model.drawer_name}}</span>
            <span class="col" v-if="model.bill_style_id != 303"><span class="hpx-label">历史交易成功率：</span>{{tradeCount}}</span>
            <span class="col" v-if="model.bill_style_id != 303"><span class="hpx-label">平均背书时长：</span>{{endorsement.minute}}分{{endorsement.second}}秒</span>
            <span class="top_btn" v-if="model.drawer_id > 0">
                <el-button type="primary" size="small" @click="$router.push(`../../stockBill/${model.drawer_id}`)">查看该企业全部库存票</el-button>
            </span>
        </el-row>
        <el-row class="detail_mian">
            <el-col :span="15" class="mian_block">
                <el-row class="title_block bill_info hpx-title-border">
                    <span class="title_text">票据信息</span>
                </el-row>
                <el-form label-width="120px" size="mini" class="detail_info">
                    <el-form-item label="票据号:">{{model.bill_number}}</el-form-item>
                    <el-form-item label="承兑人全称:">{{model.bill_acceptor_name}}</el-form-item>
                    <el-form-item label="承兑机构:">{{model.bill_acceptor_type_name}}</el-form-item>
                    <el-form-item label="票面金额:" class="hpx-red-tips"><span class="remind">{{model.bill_sum_price | numFormat}}元</span></el-form-item>
                    <el-form-item label="到期时间:">{{model.bill_deadline_time | formatDate}}(<span v-if="model.bill_remaining_day != null">剩余{{model.bill_remaining_day}}天</span><span v-if="model.bill_remaining_day == null">已过期</span>)</el-form-item>
                    <el-form-item label="汇票瑕疵:" class="hpx-red-tips">{{formatArr}}</el-form-item>
                    <el-form-item label="背书次数:">{{model.bill_endorsement_number}}</el-form-item>
                    <el-row class="imgs">
                        <el-col :span="6" :offset="1" v-if="model.bill_front_photo_id">
                            <!-- <img :src="model.bill_front_photo_path" alt=""> -->
                            <ImageZoom
                                :width='228'
                                :height='154'
                                mode='preview'
                                :image="formatPath(model.bill_front_photo_path)"
                            ></ImageZoom>
                            <el-row class="tag">票据正面</el-row>
                        </el-col>
                        <el-col :span="6" :offset="1" v-if="model.bill_back_photo_id1">
                            <!-- <img :src="model.bill_back_photo_path1" alt=""> -->
                            <ImageZoom
                                :width='228'
                                :height='154'
                                mode='preview'
                                :image="formatPath(model.bill_back_photo_path1)"
                            ></ImageZoom>
                            <el-row class="tag">背书面1</el-row>
                        </el-col>
                        <el-col :span="6" :offset="1" v-if="model.bill_back_photo_id2">
                            <!-- <img :src="model.bill_back_photo_path2" alt=""> -->
                            <ImageZoom
                                :width='228'
                                :height='154'
                                mode='preview'
                                :image="formatPath(model.bill_back_photo_path2)"
                            ></ImageZoom>
                            <el-row class="tag">背书面2</el-row>
                        </el-col>
                    </el-row>
                </el-form>
            </el-col>
            <el-col :span="9" class="mian_block">
                <el-row class="title_block bill_info hpx-title-border">
                    <span class="title_text">交易信息</span>
                </el-row>
                <el-form label-width="120px" size="mini" class="detail_info">
                    <el-form-item label="期望利率:" class="hpx-red-tips">
                        {{model.hope_rate && model.hope_rate !=0 ? model.hope_rate + '%' : '--'}}
                    </el-form-item>
                    <el-form-item label="每十万加:" class="hpx-red-tips">{{model.hope_every_plus && model.hope_every_plus != 0 ? model.hope_every_plus + '元' : '--'}}</el-form-item>
                    <el-form-item label="竞价方式:">{{model.bidding_mode == 3210 ? '一口价' : '自由竞价'}}</el-form-item>
                    <el-form-item label="发布期限:">T+{{model.trade_appoint_day}}</el-form-item>
                    <el-form-item label="期望贴现额:" class="hpx-red-tips"><span class="remind">{{model.bill_hope_deal_price | numFormat}}元</span></el-form-item>
                    <!-- bill_is_valid   -1:票已下架；0:未下架 -->
                    <el-form-item label="" class="hpx-red-tips" v-if="model.bill_is_valid == -1">该票据已下架</el-form-item>
                </el-form>
            </el-col>
        </el-row>
        <!-- 展示竞价信息：自由竞价，或者一口价并且自己参与了竞价 -->
        <el-row class="offer_info" v-if="model.bidding_mode == 3212 || (model.bidding_mode == 3210 && isBidding)">
            <p v-if="biddingsLen != 0">报价信息: 已有<span class="hpx-red-tips">{{biddingsLen}}</span>家机构报价</p>
            <p v-if="biddingsLen == 0">报价信息: 暂无报价</p>
        </el-row>
        <template>
            <Table :tableData="tableData" :operation="true" :pagination="false" v-if="model.bidding_mode == 3212 || (model.bidding_mode == 3210 && isBidding)">
                <template slot-scope="{scope}">
                    <!--
                        重新购买：竞价的第二天，卖方还未选择成交，状态变为竞价过期失效
                                或者正在竞价中，并且是自由竞价的，想重新以别的价格竞价
                     -->
                    <el-button type="primary"
                        @click="buy()"
                        v-if="(scope.row.bidding_bid_result == 3 && scope.row.is_mine == 1) || (scope.row.is_mine == 1 && model.bidding_mode == 3212 && scope.row.bidding_bid_result == 0)">
                        重新购买
                    </el-button>
                </template>
            </Table>
            <!-- 自己没有参与过竞价 -->
            <el-row class="buy_btn" v-if="!isBidding">
                <el-button type="primary" size="small" @click="buy()">我要购买</el-button>
            </el-row>
        </template>
        <!-- 竞价弹框 -->
        <!-- 一口价 -->
        <DialogInput ref="remin" title="一口价购买" v-if="model.bidding_mode == 3210">
            <div class="rem-dialog-con">
                <el-form label-width="120px" size="mini">
                    <el-form-item label="报价机构:">{{userInfo.enterprise_name}}</el-form-item>
                    <el-form-item label="年利率:" class="hpx-red-tips">{{model.hope_rate ? model.hope_rate + '%' : '--'}}</el-form-item>
                    <el-form-item label="每十万加:" class="hpx-red-tips">{{model.hope_every_plus ? model.hope_every_plus + '元' : '--'}}</el-form-item>
                    <el-form-item label="贴息:">
                        <el-row class="hpx-red-tips remind">{{form.discount_interest}}元</el-row>
                    </el-form-item>
                    <el-form-item label="平台服务费:" class="hpx-red-tips">{{form.draftbean}}个汇票豆</el-form-item>
                    <!-- <el-form-item label="总扣款额:">
                        <el-row class="hpx-red-tips">{{form.discount_amount}}元</el-row>
                    </el-form-item> -->
                    <el-form-item label="贴现金额:">
                        <el-row class="hpx-red-tips">{{form.discount_amount}}元</el-row>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="Remfooter">
                <el-button @click="closeDialog()" type="info" class="hpx-cancel-color dialog-button">取消</el-button>
                <el-button type="primary" class="dialog-button" @click="confirmBuy()">购买</el-button>
            </span>
        </DialogInput>
        <!-- 自由竞价 -->
        <DialogInput ref="remin" title="竞价" v-if="model.bidding_mode == 3212">
            <div class="rem-dialog-con">
                <el-form label-width="120px" size="mini">
                    <el-form-item label="报价机构:">{{userInfo.enterprise_name}}</el-form-item>
                    <el-form-item label="年利率:">
                        <el-col :span="20">
                            <el-input type="number" v-model="form.bid_rate" @input="inputRate()" placeholder="请输入年利率"></el-input>
                        </el-col>
                        <el-col :span="2" class="company">%</el-col>
                    </el-form-item>
                    <el-form-item label="每十万加:">
                        <el-col :span="20">
                            <el-input type="number" v-model="form.bid_every_plus" @input="inputEveryPlus()" placeholder="请输入每十万加"></el-input>
                        </el-col>
                        <el-col :span="2" class="company">元</el-col>
                    </el-form-item>
                    <!-- <el-form-item label="">
                        <el-row>贴息(元): 
                            <span class="hpx-red-tips">{{form.discount_interest == '' ? '--' : form.discount_interest}}</span>
                            (约合每十万扣款:<span class="hpx-red-tips">{{form.every_plus_amount == '' ? '--' : form.every_plus_amount}}</span>元)
                        </el-row>
                        <el-row>贴现额(元): <span class="hpx-red-tips">{{form.discount_amount == '' ? '--' : form.discount_amount}}</span></el-row>
                    </el-form-item> -->
                    <el-form-item label="贴现金额" class="hpx-red-tips">
                        {{form.discount_amount == '' ? '--' : form.discount_amount + '元'}}
                    </el-form-item>
                    <el-form-item label="平台服务费:" class="hpx-red-tips">{{form.draftbean}}个汇票豆</el-form-item>
                    <!-- <el-form-item label="总扣款额:">
                        <el-row class="hpx-red-tips">{{form.discount_amount == '' ? '--' : form.discount_amount}}元</el-row>
                    </el-form-item> -->
                </el-form>
            </div>
            <span slot="Remfooter">
                <el-button @click="closeDialog()" type="info" class="hpx-cancel-color dialog-button">取消</el-button>
                <el-button type="primary" class="dialog-button" @click="confirmBuy()">购买</el-button>
            </span>
        </DialogInput>
        <!-- 竞价成功 -->
        <DialogInput ref="bidding-success" title="竞价">
            <div class="rem-dialog-con reserva-dialog">
                <el-row class="hpx-success">
                    <i class="iconfont icon-chenggong"></i>
                </el-row>
                <el-row>
                    成功参与竞价，请等待出票方确认交易！
                </el-row>
            </div>
            <span slot="Remfooter">
                <el-button type="primary" size="small" class="dialog-button" @click="closeDialog()">确定</el-button>
            </span>
        </DialogInput>
    </div>
</template>

<script lang="ts">
    import {Vue, Component, Prop, Watch} from 'vue-property-decorator'
    import Table from '@component/common/HpxTable.vue'  
    import DialogInput from '@component/common/DialogInput.vue'  
    import moment from 'moment'
    import ImageZoom from '@component/common/ImageZoom.vue'
    import { mapState } from 'vuex';
    import { userInfo } from 'os';
    import { getEndorsementFileName1 } from '@/util/format';
    @Component({
        components:{
            Table,
            DialogInput,
            ImageZoom
        },
        computed:{
            ...mapState([
                'userInfo'
            ])
        }
    })
    export default class MyBiddingDetail extends Vue {
        @Prop(String) id!:string
    //data
        model:any = {}
        endorsement:any = {
            minute: 0,
            second: 0
        }
        tradeInfo:any = {
            finish_order_num: 0,
            real_deal_order_num: 0
        }
        biddingsLen:number = 0
        tableData:TableData = {
            header:[
                {
                    label: '报价机构',
                    key: 'bidding_enterprise_name',
                    // formatter: (row:any) => row.is_mine != 1 ? this.hideStr(row.bidding_enterprise_name) : row.bidding_enterprise_name
                },
                {
                    label: '利率',
                    key: 'bidding_bid_rate'
                },
                {
                    label: '每十万加(元)',
                    key: 'bidding_bid_every_plus'
                },
                {
                    label: '贴现额(元)',
                    key: 'bidding_bid_deal_price'
                },
                {
                    label: '约合每十万扣款(元)',
                    key: 'bidding_every_plus_interest'
                },
                {
                    label: '报价时间',
                    key: 'bidding_bid_time',
                    formatter: (row:any) => moment(row.bidding_bid_time).format('YYYY-MM-DD HH:mm:ss')
                },
                {
                    label: '状态',
                    key: 'bidding_bid_status',
                    // formatter: (row:any) => row.is_mine == 1 ? row.bidding_bid_status : ''
                }
            ],
            body: [],
            footer: {
                total: 100,
                pageSize: 10,
                currentPage: 1,
            }
        }
        form = {  
            bid_rate:'',   //利率
            bid_every_plus: '', //每十万加
            bid_deal_price: '',//总扣款额  
            every_plus_amount: '',  //约和每十万扣款
            discount_interest: '',  //贴息
            discount_amount: '',  //贴现额
            draftbean: ''//汇票豆
        }
        isBidding = false
        // xingye_bank = {}
    //methods
        //查看该企业库存票
        //toStockBill () {
            //window.location.href = 'stockBill.html?id='+this.model.drawer_id
            //this.$router.push(`stockBill/${this.model.drawer_id}`)
        //}
        formatPath (path) {
            return getEndorsementFileName1(path)
        }
        @Watch('id')
        onIdChanged (val: string, oldVal: string) {
            this.getDetailData()
        }
        //获取详细数据
        async getDetailData () {
            let res = await this.$http.get(`/bills/billProduct/${this.id}`)
            if(res.status == 200 && res.data){
                this.tableData.body = res.data.bill_biddings
                this.model = res.data
                this.biddingsLen = res.data.bill_biddings.length
                this.getIsBidding()
                if(this.model.bidding_mode == 3210 && !this.isBidding) {
                    this.buy()
                }
                if(this.model.bill_style_id != 303){
                    this.getendorsementTime()
                    this.getTradeCount()
                }
            }
        }
        //自己是否已经竞价
        getIsBidding () {
            for(let i = 0;i<this.tableData.body.length;i++){
                if(this.tableData.body[i].is_mine == 1){
                    this.isBidding = true
                }
            }
        }
        //查询企业平均背书时长
        async getendorsementTime () {
            let params = {
                enterpriseId: this.model.drawer_id
            }
            let res = await this.$http.get('customers/customer/endorsementTime',{params})
            if(res.status == 200 && res.data){
                this.endorsement = res.data
            }
        }
        //查询企业交易成功率
        async getTradeCount () {
            let res = await this.$http.get(`customers/enterpriseOrderCount/${this.model.drawer_id}`)
            if(res.status == 200){
                if(res.data){
                    this.tradeInfo = res.data
                }
            }
        }
        //计算企业交易成功率
        get tradeCount () {
            if (this.tradeInfo.real_deal_order_num == 0) {
                return '首单'
            }else{
                return parseInt(this.tradeInfo.finish_order_num/this.tradeInfo.real_deal_order_num*100)+'%'
            }
        }
        get formatArr () {
            return this.model.bill_flaw_names ? this.model.bill_flaw_names.join('，') : ''
        }
        //隐藏字符
        hideStr (value:string) {
            if(!value) return ''
            let stringArr = value.split('');
            stringArr = stringArr.slice(0, 2).concat(stringArr.slice(-2, stringArr.length));
            stringArr.splice(2, 0, '*', '*','*');
            return stringArr.join('');
        }
        //查询平台服务费
        async getServiceMonry () {
            let params = {
                acceptorTypeId: this.model.bill_acceptor_type_id,
                sumPrice: this.model.bill_sum_price
            }
            let res = await this.$http.get('/tools/calculator/comission',{params})
            if(res.status == 200){
                this.form.draftbean = res.data
                this.getDraftbean()
            }
        }
        //查询汇票豆余额
        async getDraftbean () {
            let res = await this.$http.get(`/draftbean/account/${this.userInfo.enterprise_id}`)
            if(res.status == 200 && res.data){
                if(res.data.availableBalance < this.form.draftbean){
                    this.$confirm('平台汇票豆余额不足，请充值','提示',{
                        confirmButtonText: '去充值',
                        cancelButtonText: '取消',
                        customClass: 'custom-message-box'
                    }).then(() => {
                        this.$router.push('/enterprise/draftBeans')
                    })
                }else{
                    this.$refs['remin'].openDialog();
                }
            }
        }
        //查询执剑人账户信息
        async getQuery() {
            let res = await this.$http.get('paying/xingyeapi/query')
            if(res.status == 200 && res.data && res.data.xingYeBankDtos.length > 0){
                this.getServiceMonry()
                this.model.bidding_mode == 3210 ? this.calcAmount() : ''
            }else{
                this.$confirm('你还未绑定兴业账户','提示',{
                    confirmButtonText: '去绑定',
                    cancelButtonText: '取消',
                    customClass: 'custom-message-box'
                }).then(() => {
                    this.$router.push('/enterprise/judge')
                })
            }
        }
        // async getQuery() {
        //     this.getServiceMonry()
        //     this.model.bidding_mode == 3210 ? this.calcAmount() : ''
        // }
        //竞价弹框
        buy () {
            this.getQuery()
        }
        closeDialog () {
            this.$refs['remin'].closeDialog();
            this.$refs['bidding-success'].closeDialog()
        }
        //贴息计算
        async calcAmount () {
            let calculatorReq = {
                start_time: moment(new Date()).format('YYYY-MM-DD'),
                end_time: moment(this.model.bill_deadline_time).format('YYYY-MM-DD'),
                denomination: this.model.bill_sum_price/10000,  //票面金额
                interest_year: this.model.bidding_mode == 3212 ? this.form.bid_rate : this.model.hope_rate,     //利率
                every_plus:  this.model.bidding_mode == 3212 ? this.form.bid_every_plus : this.model.hope_every_plus   //每十万加
            }
            let res = await this.$http.post('/tools/calculator?func=mix',calculatorReq,{},{loading:false})
            if(res.status == 200 && res.data){
                this.form.discount_interest = res.data.discount_interest//贴息金额
                this.form.every_plus_amount = res.data.every_plus_amount//约和每十万扣款
                this.form.discount_amount = res.data.discount_amount //贴现额
            }
        }
        //输入利率
        inputRate () {
            this.calcAmount()
        }
        //输入每十万加
        inputEveryPlus () {
            this.calcAmount()
        }
        //提交竞价
        confirmBuy () {
            this.bidding()
        }
        
        async bidding () {
            if(this.model.bidding_mode == 3212 && (!this.form.bid_rate && !this.form.bid_every_plus)){
                this.$alert('请填写利率和每十万加','提示',{
                    confirmButtonText: '确定',
                    customClass: 'custom-message-box'
                })
                return;
            }
            let billProductBiddingReq = {
                bill_product_id: this.model.bill_product_id,
                bid_rate: this.model.bidding_mode == 3212 ? this.form.bid_rate : this.model.hope_rate,                       //利率
                bid_rate_price: Number(this.form.discount_interest),//贴息金额
                bid_deal_price: Number(this.form.discount_amount),  //成交金额
                bid_every_plus: this.model.bidding_mode == 3212 ? Number(this.form.bid_every_plus) : this.model.hope_every_plus //每十万贴息/每十万加
            }
            let res:any = await this.$http.post('/bills/bidding',billProductBiddingReq)
            if(res.status == 200){
                this.$refs['bidding-success'].openDialog()
                this.$refs['remin'].closeDialog()
                this.getDetailData()
            }
            // else{
            //     this.$alert(res.msg,'提示',{
            //         confirmButtonText: '确定',
            //         customClass: 'custom-message-box'
            //     })
            // }
        }
        mounted() {
            this.getDetailData()
            
        }
    }
</script>

<style lang="scss" scoped>
    .enterprise_info{
        height: 50px;
        line-height: 50px;
        // .col{
        //     margin-left: 50px;
        // }
        .top_btn{
            float: right;
            margin-right: 40px;
        }
    }
    .bill_info{
        height: 30px;
        line-height: 30px;
    }
    .detail_mian{
        .mian_block{
            height: 594px;
            .imgs{
                .el-col{
                    // width: 228px;
                    .image_zoom{
                        width: 100%;
                        border: 1px solid $__color-border;
                    }
                }
            }
        }
    }
    .el-form-item__label{
        color: $__color-label !important;
    }
    .el-form-item--mini .el-form-item__content, .el-form-item--mini .el-form-item__label {
        line-height: 20px !important;
    }

    .offer_info{
        margin-top: 20px;
        height: 30px;
        line-height: 30px;
        border-bottom: 1px solid $__color-primary;
        color: $__color-label;
        font-size: 18px;
    }
    .buy_btn{
        text-align: right;
        margin-top: 10px;
    }
    .rem-dialog-con{
        text-align: left;
    }
    .reserva-dialog{
        text-align: center;
        .hpx-success{
            font-size: 30px !important;
            margin-bottom: 12px !important;
        }
    }
    .company{
        text-align: center;
    }
    .remind{
        font-size: 20px;
    }
</style>